package com.ecut.drug_bid.service;

import com.ecut.drug_bid.domain.Bid;
import com.ecut.drug_bid.domain.Tender;
import com.ecut.drug_bid.dto.BidCreateRequest;
import com.ecut.drug_bid.repository.BidRepository;
import com.ecut.drug_bid.repository.TenderRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class BidService {

    private final BidRepository bidRepository;
    private final TenderRepository tenderRepository;

    // 查询所有投标信息
    public List<Bid> findAll() {
        return bidRepository.findAll();
    }

    // 根据招标项目编号查询投标列表
    public List<Bid> findByTenderCode(String tenderCode) {
        return bidRepository.findByTenderCode(tenderCode);
    }

    // 根据投标单位用户ID查询
    public List<Bid> findByBidderUserId(Long bidderUserId) {
        return bidRepository.findByBidderUserId(bidderUserId);
    }

    // 根据ID查询
    public Optional<Bid> findById(Long id) {
        return bidRepository.findById(id);
    }

    // 提交投标（仅投标单位）
    @Transactional
    public Bid create(BidCreateRequest request, Long bidderUserId) {
        // 检查招标项目是否存在
        Tender tender = tenderRepository.findById(request.getTenderCode())
            .orElseThrow(() -> new RuntimeException("招标项目不存在"));

        // 检查是否已过截止日期
        if (LocalDateTime.now().isAfter(tender.getDeadline())) {
            throw new RuntimeException("招标已截止");
        }

        Bid bid = new Bid();
        bid.setBidDate(LocalDateTime.now());
        bid.setBidderOrg(request.getBidderOrg());
        bid.setLegalName(request.getLegalName());
        bid.setContactPhone(request.getContactPhone());
        bid.setTenderCode(request.getTenderCode());
        bid.setProductBatch(request.getProductBatch());
        bid.setMfgDate(request.getMfgDate());
        bid.setExpiryDate(request.getExpiryDate());
        bid.setTotalAmount(request.getTotalAmount());
        bid.setDepositPaidAt(request.getDepositPaidAt());
        bid.setBidderUserId(bidderUserId);

        return bidRepository.save(bid);
    }

    // 删除投标（仅投标单位本人或管理员）
    @Transactional
    public void delete(Long bidId) {
        if (!bidRepository.existsById(bidId)) {
            throw new RuntimeException("投标信息不存在");
        }
        bidRepository.deleteById(bidId);
    }
}